package com.onec.service.unsafe.collection;

import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

public class CollectionDemo {


  // 同步容器处理 一旦锁升级魏重量级锁影响性能：
  public static void main(String[] args) {
    SortedSet<String> pri = new TreeSet<>();
    pri.add("111");
    pri.add("22222");

    // 将map 转为同步容器
    //Collections.synchronizedSortedMap();
    // 将list 包装为同步容器
    //Collections.synchronizedList(new ArrayList<>());

    // 将set 包装成同步容器
    SortedSet<String> sortedSet = Collections.synchronizedSortedSet(pri);
    CountDownLatch downLatch = new CountDownLatch(5);

    for (int i = 0; i < 5; i++) {
      int finalI = i;
      Executors.newFixedThreadPool(1).submit(new Runnable() {
        @Override
        public void run() {
          sortedSet.add(String.valueOf(finalI));

          downLatch.countDown();
        }
      });
    }
    try {
      downLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    sortedSet.forEach(System.out::println);
  }
}
